package cn.yuan.org.controller;

import cn.yuan.basic.util.LoginContext;
import cn.yuan.basic.util.PageList;
import cn.yuan.org.domain.Department;
import cn.yuan.org.query.DepartmentQuery;
import cn.yuan.org.service.IDepartService;
import cn.yuan.util.AjaxResult.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/department")
@Api(tags = "部门接口",description = "部门接口详细描述")
public class DepartmentController {
    @Autowired
    private IDepartService departService;

    @GetMapping("/{id}")
    @ApiOperation(value = "部门查找",notes = "根据ID查找部门")
    public Department loadById(@PathVariable("id")Long id){
        return departService.loadById(id);
    }

    @GetMapping
    @ApiOperation(value = "查询所有部门")
    public List<Department> findAll(){
        return departService.loadAll();
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除部门",notes = "根据ID删除部门")
    public AjaxResult remove(@PathVariable("id") Long id){
        try {
            departService.remove(id);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("删除失败");
        }
    }

    @PatchMapping
    @ApiOperation(value = "批量删除部门",notes = "根据ID删除部门")
    public AjaxResult batchDel(@RequestBody Long[] ids){
        System.out.println(ids);
        try {
            departService.batchDel(ids);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("删除失败");
        }
    }

    @PutMapping
    @ApiOperation(value = "添加或者修改部门",notes = "添加或者修改部门")
    public AjaxResult addOrUpdate(@RequestBody Department department){
        try {
            if(department.getId()==null){
                departService.save(department);
            }else {
                departService.update(department);
            }
            return new AjaxResult();
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("操作失败");
        }
    }

    @PostMapping
    @ApiOperation(value = "查询分页",notes = "分页查询部门")
    public PageList<Department> queryForPage(@RequestBody DepartmentQuery departmentQuery, HttpServletRequest request){
        System.out.println("========当前登录人信息======="+ LoginContext.getLoginInfo(request));
        return departService.queryForPage(departmentQuery);
    }

    //获取所有 get
    @GetMapping("/depttree")
    @ApiOperation(value = "查询上级部门",notes = "")
    public List<Department> deptTree(){
        return departService.getDeptTree();
    }
}
